package cn.caixiong.basic.util;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

//oss文件操作的工具类
public class MyFileUtils {
    public static String fileUpload(MultipartFile file){
        // 1. 拿到原始的文件名
        String originalFilename = file.getOriginalFilename();
        // 2. 拿到文件名的后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        // 3. 随机生成一个文件名
        String newFileName = UUID.randomUUID().toString();
        // 4. 拼接最终存储在OSS服务器上的文件路径和文件名   exampledir/x2d2f5fd52dv2dv5df555df8322.png
        String objectName = Constants.OBJECT_NAME + "/" + newFileName + "." + suffix;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("HTTPS://" + Constants.ENDPOINT, Constants.ACCESS_KEY, Constants.SECRET_KEY);
        try {
            // 创建PutObject请求,并上传文件
            ossClient.putObject(Constants.BUCKET_NAME, objectName, file.getInputStream());
            return "https://" + Constants.BUCKET_NAME + "." + Constants.ENDPOINT + "/" + Constants.OBJECT_NAME + "/" + newFileName + "." + suffix;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return null;
    }
}
